'''
Description: 
Author: Zilu
Date: 2021-11-18 13:10:04
Version: 
LastEditTime: 2021-11-18 20:54:01
LastEditors: Zilu
'''

# asyncio 内置了对异步 IO 的支持，其编程模型就是一个消息循环
# import asyncio, threading
# from os import write
# from asyncio import tasks

# @asyncio.coroutine
# def hello():
#     print('Hello world (%s)' % threading.current_thread())
#     # 异步调用asyncio.sleep
#     # yield from后面加上可迭代对象，可以把可迭代对象里的每个元素一个一个的yield出来
#     # yield from后面加上生成器，实现生成的嵌套 
#     r = yield from asyncio.sleep(1)
#     print('Hello world (%s)' % threading.current_thread())

# # 获取Eventloop
# loop = asyncio.get_event_loop()
# tasks = [hello(), hello()]
# # 执行coroutine
# # 并发执行
# loop.run_until_complete(asyncio.wait(tasks))
# loop.close()

# 使用异步网络连接获取sina、sohu和163的首页信息
import asyncio

@asyncio.coroutine
def wget(host):
    print('wget %s...' % host)
    connect = asyncio.open_connection(host, 80)
    reader, writer = yield from connect
    header = 'GET /HTTP/1.0\r\nHost: %s\r\n\r\n' % host
    writer.write(header.encode('utf-8'))
    yield from writer.drain()
    while True:
        line = yield from reader.readline()
        if line == b'\r\n':
            break
        print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
        # Ingore body, close the socket
    writer.close()

loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

# asyncio提供了完善的异步IO支持；
# 异步操作需要在coroutine中通过yield from完成；
# 多个coroutine可以封装成一组Task然后并发执行。

# 为了更好地标识异步IO，python 3.5 开始引入新的语法
# 把@asyncio.coroutine替换为async；
# 把yield from替换为await。
# 其他步骤不变

